<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="searchChange" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" :data="depts" :props="defaultProps" default-expand-all :expand-on-click-node="false" highlight-current @current-change="selectNode" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username.charAt(row.username.length -1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" align="center" />
          <el-table-column prop="mobile" label="手机号" sortable align="center" />
          <el-table-column prop="workNumber" label="工号" sortable align="center" />
          <el-table-column prop="formOfEmployment" label="聘用形式" align="center">
            <template v-slot="{row}">
              <span>{{ row.formOfEmployment===1? "正式" : row.formOfEmployment ===2? "非正式" : "无" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" align="center" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable align="center" />
          <el-table-column label="操作" align="center" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail?id=${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" style="margin-right:10px" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="这是条员工信息确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height:60px" type="flex" justify="end" align="middle">
          <el-pagination :total="total" :page-size="queryParams.pagesize" :current-page="queryParams.page" layout="total,prev, pager, next" @current-change="pageChange" />
        </el-row>
      </div>
    </div>
    <!-- 导入员工的弹出框 -->
    <import-excel-vue :show-excel-dialog.sync="showExcelDialog" @importSuccess="importSuccess" />
    <!-- 角色权限弹出框 -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" style="width:70px;margin-top:15px" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="4">
          <el-button size="mini" type="primary" @click="btnRoleOk">确定</el-button>
          <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { transformListToTreeData } from '@/utils'
import { getEmployeeList, exportEmployee, delEmployee, getEnableRoles, getEmployeeDetail, assignRoles } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcelVue from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcelVue
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      total: 0, // 数据总数
      queryParams: {
        departmentId: null, // 部门id
        page: 1, // 页码
        pagesize: 10, // 页容量
        keyword: '' // 搜索关键字
      },
      list: [], // 数据列表
      roleList: [], // 角色列表
      roleIds: [], // 角色id集合
      currentUserId: null,
      showExcelDialog: false, // 是否显示导入Excel的对话框
      showRoleDialog: false // 是否显示角色的对话框
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      // 获取部门数据并转化成树形结构
      this.depts = transformListToTreeData(await getDepartmentList(), 0)
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // 调用获取员工列表
      this.getEmployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      // 部门id变化重新获取员工列表
      this.getEmployeeList()
    },
    async getEmployeeList() {
      // 获取员工列表数据
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.total = total
      this.list = rows
    },
    pageChange(newPage) {
      // 更新页码
      this.queryParams.page = newPage
      // 重新获取员工数据列表
      this.getEmployeeList()
    },
    searchChange() {
      // 清除计时器：防抖处理
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    async exportEmployee() {
      const result = await exportEmployee()
      FileSaver.saveAs(result, '员工信息表.xlsx')
    },
    // 导入成功
    importSuccess() {
      // 将页码重置为第一页
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 删除员工
    async delEmployee(id) {
      await delEmployee(id)
      // 如果是最后一条数据，当前页码要往前翻一页
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.$message.success('删除员工成功')
      // 重新获取员工列表
      this.getEmployeeList()
    },
    // 显示分配权限列表
    async btnRole(id) {
      this.currentUserId = id
      this.roleList = await getEnableRoles()
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async btnRoleOk() {
      await assignRoles({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('角色分配权限成功！')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
